<template>
  <div class="home">
    <div class="login">
      <div class="login-title">{{ indexStore.BackOperator }} {{ indexStore.is_general_agent ? '总代后台' : '总控运营后台' }}</div>
      <div class="form">
        <div class="avatar">
          <img class="avatar-img" src="@/assets/images/user-default.png" alt="" />
        </div>
        <el-form ref="form" :model="loginForm" :rules="rules" label-width="0" class="demo-ruleForm" status-icon>
          <el-form-item prop="username">
            <el-input size="large" v-model="loginForm.username" placeholder="请输入账号" autocomplete="off">
              <template #prefix>
                <el-icon size="24">
                  <User />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input size="large" type="password" show-password v-model="loginForm.password" placeholder="请输入密码"
              autocomplete="off">
              <template #prefix>
                <el-icon size="24">
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="google_code">
            <el-input size="large" v-model="loginForm.google_code" placeholder="请输入谷歌验证码" autocomplete="off">
              <template #prefix>
                <el-icon size="24">
                  <Bell />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button class="login-btn" type="primary" @click="login" v-loading="loading">登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { userLogin, simulatedOperatorLogin } from '@/api/user'
import { Time } from '@/utils/serverTime'
import { LocalPath } from '@/config/eunm'
import { selectToLabel, OperatorServerBrand } from '@/utils/index'

import { useStore } from '@/stores/index'
const indexStore = useStore()
import { useRouter } from 'vue-router'
import type { Res } from '@/utils/request'
const router = useRouter()

interface RuleForm {
  username: string
  password: string
  google_code: string
}

indexStore.BackOperator = OperatorServerBrand('label') //运营商名字区分
indexStore.BackServer = OperatorServerBrand('remark') //运营商服务器区分

// 登录
let loading = ref(false)
const form = ref<FormInstance>()
const loginForm = reactive<RuleForm>({
  username: '',
  password: '',
  google_code: ''
})
const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: '请输入', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入', trigger: 'blur' },
    { min: 6, max: 16, message: '密码最少输入六位', trigger: 'blur' }
  ]
})
const login = async () => {
  if (!form) return
  await form.value?.validate(async (valid: any, fields: any) => {
    if (valid) {
      loading.value = true;
      try {
        let query = JSON.parse(JSON.stringify(loginForm))
        query.google_code = Number(query.google_code)
        let res = await userLogin(query)
        loginPath(res)
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
  })
}

const loginPath = (res: Res<any>) => {
  // 设置时区
  Time.setGlobalTimeZoneName(res.data.offset)
  indexStore.setOffset(res.data.offset) //缓存时区偏移量
  // 设置token到localstorage
  sessionStorage.setItem('PGtoken', res.data.token)
  localStorage.setItem('navbars', JSON.stringify(res.data.navbars))
  localStorage.setItem('permission', JSON.stringify(res.data.permission))
  res.data.user_info.first_login = res.data.first_login
  res.data.user_info.is_general_agent = res.data.is_general_agent
  res.data.user_info.operator_type = res.data.operator_type
  res.data.user_info.is_multi_currency = res.data.is_multi_currency
  res.data.user_info.server_name_id = res.data.server_name_id
  res.data.user_info.kol = res.data.kol
  indexStore.setUserInfo(res.data.user_info) //用户信息

  indexStore.getGame() //游戏汇总
  indexStore.getOperator() //总代汇总
  indexStore.getAgent() //商户汇总
  indexStore.getCurrent() //货币汇总
  indexStore.getExchange() //货币汇率汇总
  indexStore.getServerName() //全球服名称
  
  indexStore.breadArray = []
  indexStore.pathArray = []
  res.data.navbars?.forEach((item:any) => {
    if(item.children){
      item.children.forEach((second:any) => {
        indexStore.pathArray.push({meta:{name:selectToLabel(LocalPath,second.title),title:second.title},name:selectToLabel(LocalPath,second.title),path:second.path})
      })
    }else{
      indexStore.pathArray.push({meta:{name:selectToLabel(LocalPath,item.title),title:item.title},name:selectToLabel(LocalPath,item.title),path:item.path})
    }
  })
  
  // 判断是否是总代 1是总代 0不是总代
  if (res.data.is_general_agent) {
    res.data.permission.push('General.agency')
    indexStore.is_general_agent = true
  } else {
    indexStore.is_general_agent = false
  }
  // 跳转问题
  pathReplace(res,indexStore.pathArray) 
  return reload()
}

// 路径跳转
const pathReplace = async (res:any,pathList:any) => {
  // 1.正常总代跳转商户管理页面(首次) 2.多货币总代跳转API接入页面(首次)
  if(res.data.is_skip){
    // 判断用户是否包含仪表盘
    if(pathLogin('panel')){
      indexStore.breadArray.push({meta:{name:'panel',title:'仪表盘'},name:'panel',path:'/panel'})
    }
    if(res.data.is_multi_currency){
      // 都不包含则跳转 数组第一个
      if(!pathLogin('document') && !pathLogin('panel')){
        router.replace({ path: pathList[0].path })
        indexStore.breadArray=[pathList[0]]
        return reload()
      }
      // 判断用户是否包含API接入
      if(pathLogin('document')){
        router.replace({ path: '/document' })
        indexStore.breadArray.push({meta:{title:'API接入',name:'document'},name:'document',path:'/document'})
        return reload()
      }
    }else if(res.data.is_general_agent){
      if(pathLogin('merchant')){
        router.replace({ path: '/merchant/merchant' })
        indexStore.breadArray.push({meta:{title:'商户列表',name:'merchant'},name:'merchant',path:'/merchant/merchant'})
      }else{
        router.replace({ path: pathList[0].path })
        indexStore.breadArray=[pathList[0]]
      }
      return reload()
    }
  }
  // 跳转数组第一个
  if(pathLogin('panel')){
    router.replace({ path: pathList[0].path })
    indexStore.breadArray = [{meta:{name:'panel',title:'仪表盘'},name:'panel',path:'/panel'}]
  }else{
    router.replace({ path: pathList[0].path })
    indexStore.breadArray = [pathList[0]]
  }
  return reload()
}
// 登录路径查询
const pathLogin = (name: string) => {
  if(indexStore.pathArray.find((item:any) => item.name == name)){
    return true
  }else{
    return false
  }
}

// 刷新
const reload = inject("reload") as any
// 总代模拟登录
const zdLogin = async (id: number) => {
  let res = await simulatedOperatorLogin({ operated_id: id,token:sessionStorage.getItem('PGtoken') ? sessionStorage.getItem('PGtoken') : '' })
  loginPath(res)
}

defineExpose({
  zdLogin
})
</script>
<style scoped lang="scss">
.home {
  width: 100%;
  height: 100%;
  display: flex;
  background: url('@/assets/images/bg.jpg');
  align-items: center;
  justify-content: center;

  // min-width: 1280px;
  .login {
    width: 430px;
    height: 500px;
    background: #fff;

    .login-title {
      height: 150px;
      width: 100%;
      background: url('@/assets/images/login-header.png') no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      color: #000;
      font-weight: bold;
    }
  }

  .form {
    padding: 80px 40px 10px;
    position: relative;

    .avatar {
      position: absolute;
      left: 50%;
      top: -50px;
      transform: translate(-50px, 0);
      border: 4px solid #fff;
      border-radius: 50%;

      .avatar-img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
    }

    .login-btn {
      width: 100%;
      height: 40px;
    }
  }
}
</style>